ItemPage = function(mainPage){
	this.mainPage = mainPage;
	this.item_id = null;
	this.answer = null;
	this.passageView = new ItemPassageView();
	this.questionView = new ItemQuestionView();
	this.optionView = new ItemOptionView(this);
	
	ItemPage.superclass.constructor.call(this, {
		id: 'item_main_page',
		autoHeight: true,
		cls: 'item-view',
		scroll: 'vertical',
		layout: {type: 'vbox', pack: 'start', align:'stretch'},
		items: [{
			items: this.passageView
		},{
			items: this.questionView
		},{
			items: this.optionView
		}]
	});
};

Ext.extend(ItemPage, Ext.Panel, {
	setAnswer: function(answer){
		this.answer = answer;
		if(answer){
			this.mainPage.setPIndex('testing');
		}else{
			this.mainPage.setPIndex('testing_skip');
		}
	},
	requestItem: function(){
		var page = this;
		showMask({message:'Load item..', cls : 'waiting-mask'});
		Ext.Ajax.request({
            url: "/cat/select_item",
            params: {
				theta: userProfile.getTheta()
            },
            success: function(response){
                json = Ext.util.JSON.decode(response.responseText);
                if (!json.success) {
                	Ext.Msg.alert('Error!!', json.message, Ext.emptyFn);
					hideMask();
					return;
                }
				page.item_id = json.data.item.id;
				page.passageView.setPassage(json.data.passage);
				page.questionView.setQuestion(json.data.item);
				page.optionView.setOptions(json.data.item.options);
				userProfile.setTheta(json.data.theta);
				
				hideMask();
				page.doLayout();
            },
			failure: function(){
				Ext.Msg.alert('Error!!', 'Network Error!!', Ext.emptyFn);
				hideMask();
			}
        });
	},
	requestAnswering: function(){
		var page = this;
		showMask({message:'Answering..', cls : 'waiting-mask'});
		Ext.Ajax.request({
            url: "/cat/answer",
            params: {
				item_id: page.item_id,
				answer: page.answer,
				theta: userProfile.getTheta()
            },
            success: function(response){
                json = Ext.util.JSON.decode(response.responseText);
                if (!json.success) {
                	Ext.Msg.alert('Error!!', json.message, Ext.emptyFn);
					hideMask();
					return;
                }
				userProfile.setTheta(json.data.theta);
				if(json.data.has_next_step){
					hideMask();
					page.requestItem();
				}else{
					hideMask();
					page.mainPage.stopCAT();
				}
            },
			failure: function(){
				Ext.Msg.alert('Error!!', 'Network Error!!', Ext.emptyFn);
				hideMask();
			}
        });
	},
	nextItem: function(withAnswering){
		var page = this;
		if(!this.isVisible()){
			this.show(true);
			this.passageView.show(true);
			this.questionView.show(true);
			this.optionView.show(true);
		}
		
		if(withAnswering){
			this.requestAnswering();
		}else{
			this.requestItem();
		}
	}
});